package yt.spider;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import yt.spider.activity.ImportBookActivity;
import yt.spider.adapter.FragmentAdapter;
import yt.spider.bean.BookShelfBean;
import yt.spider.help.BookshelfHelp;
import yt.spider.widget.main.BookShelfFragment;
import yt.spider.widget.main.ClassifyFragment;
import yt.spider.widget.main.ExperimentFragment;

import static yt.spider.R.id.dl_main_drawer;

public class MainActivity extends AppCompatActivity {
    private ViewPager mViewPager;
    private TabLayout mTabLayout;
    private DrawerLayout mDrawerLayout;
    private Toolbar mToolbar;
    private static int judge = 1;   //判断变量

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (judge == 1) {     //此判断载入主布局文件
            setContentView(R.layout.factivity_main);  //滑动显示toolbar
        } else {
            setHideToolBar();   //滑动隐藏toolbar
        }

        setToolBar();      //设置ToolBar组件一系列配置
        initViewPager();   //设置TabLayout的一系列配置函数
        setNavigation();   //载入一系列Navigation设置的函数
        setMenuClick();


    }

    private void setMenuClick() {
        judge = 1;
        mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_show:
                        Toast.makeText(MainActivity.this, "重启后，将固定Toolbar", Toast.LENGTH_SHORT).show();
                        judge = 1;
                        break;
                    case R.id.action_hide:
                        judge = 2;
                        Toast.makeText(MainActivity.this, "重启后，滑动将隐藏Toolbar", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.action_about:
                        Toast.makeText(MainActivity.this, "爬虫阅读", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
    }

    //初始化Action menu,显示出tool在menu中设置的一系列控件
    public void setToolBar()
    //该函数设置调出侧滑三条杠图标和返回图标，并让其一起联动的设置
    {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);  //设置toolbar
        setSupportActionBar(mToolbar);    //载入toolbar

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);  //返回箭头出现函数设置
        //下面三段是三条杠图标出现一系列设置
        mDrawerLayout = (DrawerLayout) findViewById(R.id.dl_main_drawer);
        ActionBarDrawerToggle mToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.string.drawer_open, R.string.drawer_close);
        mToggle.syncState();
        mDrawerLayout.addDrawerListener(mToggle);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        //为toolbar调用menu文件里menu_tool的布局
        getMenuInflater().inflate(R.menu.menu_tool, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                //  Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_SHORT).show();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //滑动隐藏toolbar
    public void setHideToolBar() {
        setContentView(R.layout.activity_main_hide);
        //final ActionBar ab = getSupportActionBar();
        //ab.setDisplayHomeAsUpEnabled(true);
    }


    //下部分为Navigation组件相关必要代码
    public void setNavigation() {
        //设置Navigation组件的相关代码
        mDrawerLayout = (DrawerLayout) findViewById(dl_main_drawer);
        NavigationView navigationView =
                (NavigationView) findViewById(R.id.nv_main_navigation);
        if (navigationView != null) {
            navigationView.setNavigationItemSelectedListener(
                    new NavigationView.OnNavigationItemSelectedListener() {
                        @Override
                        public boolean onNavigationItemSelected(MenuItem menuItem) {
                            // 改变item选中状态
                            menuItem.setChecked(true);
                            String title = menuItem.getTitle().toString();
                            Toast.makeText(getApplicationContext(), title, Toast.LENGTH_SHORT).show();
                            //关闭导航菜单
                            mDrawerLayout.closeDrawers();
                            switch (menuItem.getItemId()) {
                                case R.id.nav_home:
                                    startActivity(new Intent(MainActivity.this, ImportBookActivity.class));
                                    break;
                                default:
                                    break;
                            }
                            return true;
                        }
                    });
        }
    }


    //下面是TabLayout相关代码
    private void initViewPager() {
        mTabLayout = (TabLayout) findViewById(R.id.tabs);
        mViewPager = (ViewPager) findViewById(R.id.viewpager);

        List<String> titles = new ArrayList<>();
        titles.add("书架");
        titles.add("分类");
        titles.add("实验室");

        for (int i = 0; i < titles.size(); i++) {
            mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(i)));
        }
        List<Fragment> fragments = new ArrayList<>();

        fragments.add(new BookShelfFragment());
        fragments.add(new ClassifyFragment());
        fragments.add(new ExperimentFragment());

        FragmentAdapter mFragmentAdapteradapter =
                new FragmentAdapter(getSupportFragmentManager(), fragments, titles);
        //给ViewPager设置适配器
        mViewPager.setAdapter(mFragmentAdapteradapter);
        //将TabLayout和ViewPager关联起来。
        mTabLayout.setupWithViewPager(mViewPager);
        //给TabLayout设置适配器
        mTabLayout.setTabsFromPagerAdapter(mFragmentAdapteradapter);
    }

    public void queryBookShelf(final Boolean needRefresh) {
        Observable.create((ObservableOnSubscribe<List<BookShelfBean>>) e -> {
            List<BookShelfBean> bookShelfList = BookshelfHelp.getAllBook();
            e.onNext(bookShelfList == null ? new ArrayList<>() : bookShelfList);
            e.onComplete();
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SimpleObserver<List<BookShelfBean>>() {
                    @Override
                    public void onNext(List<BookShelfBean> value) {
                        if (null != value) {
                            //mView.refreshBookShelf(value);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }
                });
    }
}